<?php

class AdminController extends RController
{
	public $defaultAction = 'admin';
	public $layout = '//layouts/lay_column2';
	public $menu=array();
	
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}
	
	public function init()
	{
		$this->menu = Yii::app()->params['system'];
	}
	
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','create','update','view'),
				'users'=>UserModule::getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$isAdmin = Yii::app()->getModule('user')->isAdmin();
		$user = User::model()->findByPk(Yii::app()->user->id);
		$unit_ids = array();
		$user_ids = array();
		$city_ids = array();
		$county_ids = array();
		if(!$isAdmin){
			switch($user->unit_level){
				case 1:
					$provs = MtsysProvince::model()->findAll('PROVINCE_ID=:pid',array(':pid'=>$user->unit_id));
					foreach($provs as $prov){
						$condition = 'unit_id = :prov_id And unit_level = :level';
						$params = array(':prov_id' => $prov->PROVINCE_ID,
								':level' => '1');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;					
						}
					}
					
					$citys = MtsysCity::model()->findAll('PROVINCE_ID=:pid',array(':pid'=>$user->unit_id));
					foreach($citys as $city){
						$condition = 'unit_id = :city_id And unit_level = :level';
						$params = array(':city_id' => $city->CITY_ID, 
										':level' => '2');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;	
							$city_ids[] = $_user->unit_id;
						}
					}
					//var_dump($user_ids);
					
					$countys = MtsysCounty::model()->findAll('CITY_ID in (:cids)', array(':cids'=>implode(',',$city_ids)));
					foreach($countys as $county){
						$condition = 'unit_id = :county_id And unit_level = :level';
						$params = array(':county_id' => $county->COUNTY_ID,
								':level' => '3');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;
							$county_ids[] = $county->COUNTY_ID;	
						}
					}
					
					$bases = MtsysBase::model()->findAll('PROVINCE_ID=:pid',array(':pid'=>$user->unit_id));
					foreach($bases as $base){
						/*$condition = 'unit_id = :base_id And unit_level = :level';
						$params = array(':base_id' => $base->BASE_ID,
								':level' => '4');
						$_user = User::model()->find($condition, $params);
						if($_user){
							$user_ids[] = $_user->id;
							$unit_ids[] = $base->BASE_ID;	
						}*/
						$users = MtsysBase::model()->getUserIds($base->BASE_ID);
						foreach ($users as $_user){
							array_push($user_ids,$_user->id);
						}
					}
					
					$unit_ids[] = $user->unit_id;
					
					break;
				case 2:
					$citys = MtsysCity::model()->findAll('CITY_ID=:cid',array(':cid'=>$user->unit_id));
					foreach($citys as $city){
						$condition = 'unit_id = :city_id And unit_level = :level';
						$params = array(':city_id' => $city->CITY_ID,
								':level' => '2');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;
							$city_ids[] = $_user->unit_id;
						}
					}
					
					$countys = MtsysCounty::model()->findAll('CITY_ID=:cid',array(':cid'=>$user->unit_id));
					foreach($countys as $county){
						$condition = 'unit_id = :county_id And unit_level = :level';
						$params = array(':county_id' => $county->COUNTY_ID,
								':level' => '3');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;
							$county_ids[] = $county->COUNTY_ID;	
						}
					}
					
					$bases = MtsysBase::model()->findAll('CITY_ID=:pid',array(':pid'=>$user->unit_id));
					foreach($bases as $base){
						$users = MtsysBase::model()->getUserIds($base->BASE_ID);
						foreach ($users as $_user){
							array_push($user_ids,$_user->id);
						}
					}
					$unit_ids[] = $user->unit_id;
					
					break;
				case 3:
					$countys = MtsysCounty::model()->findAll('COUNTY_ID=:cid',array(':cid'=>$user->unit_id));
					foreach($countys as $county){
						$condition = 'unit_id = :county_id And unit_level = :level';
						$params = array(':county_id' => $county->COUNTY_ID,
								':level' => '3');
						$_users = User::model()->findAll($condition, $params);
						foreach($_users as $_user){
							$user_ids[] = $_user->id;
							$county_ids[] = $county->COUNTY_ID;
						}
					}
					
					$bases = MtsysBase::model()->findAll('COUNTY_ID=:pid',array(':pid'=>$user->unit_id));
					foreach($bases as $base){
						$users = MtsysBase::model()->getUserIds($base->BASE_ID);
						foreach ($users as $_user){
							array_push($user_ids,$_user->id);
						}
					}
					$unit_ids[] = $user->unit_id;
					break;
				case 4:				
					$user_ids[] = $user->id;
					/*if(strripos($user->unit_id,',')){
					$bases = MtsysBase::model()->findAll('BASE_ID in (:bids)', array(':bids'=>$user->unit_id));		
					}else{
					$bases = MtsysBase::model()->findAll('BASE_ID=:bid',array(':bid'=>$user->unit_id));
					}
					foreach($bases as $base){
						$condition = 'unit_id = :base_id And unit_level = :level';
						$params = array(':base_id' => $base->BASE_ID,
								':level' => '4');
						$_user = User::model()->find($condition, $params);
						if($_user){
							$user_ids[] = $_user->id;
							$unit_ids[] = $base->BASE_ID;	
						}
					}
					$unit_ids[] = $user->unit_id;*/
					break;	
			}	
		}
		
		$criteria=new CDbCriteria;
		$criteria->condition = ($isAdmin)?'':'id in ('.implode(',',$user_ids).') ' ;
		//$criteria->compare('unit_level','2',true);
		
		$dataProvider=new CActiveDataProvider('User', array(
			/*'criteria'=>array(
				'condition'=>($isAdmin)?'':'unit_id in ('.implode(',',$unit_ids).')',			
			),*/
				'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>Yii::app()->controller->module->user_page_size,
			),
		));
		
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}


	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$model = $this->loadModel();
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;
		$profile=new Profile;
		if(isset($_POST['User']))
		{
			//var_dump($_POST['User']);
			$model->attributes=$_POST['User'];
			$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
			$model->createtime=time();
			$model->lastvisit=time();
			switch($_POST['User']['unit_level']){
				case '1':
					$model->unit_id = $_POST['User']['PROVINCE_ID'];
					break;
				case '2':
					$model->unit_id = $_POST['User']['CITY_ID'];
					break;
				case '3':
					$model->unit_id = $_POST['User']['COUNTY_ID'];
					break;
				case '4':
					if(isset($_POST['User']['BASE_ID'])){
						//$model->unit_id = $_POST['User']['BASE_ID'];
						if(is_array($_POST['User']['BASE_ID'])){
							echo "array";
							$model->unit_id = implode(',',$_POST['User']['BASE_ID']);
						}else{
							echo "single";
							$model->unit_id = $_POST['User']['BASE_ID'];
						}
					}else{
						$error = '请确认已选择站点和省市区单位' ;
						throw new CHttpException(404, $error);
					}
										
					break;
			}
			if(empty($model->email)){
			  $model->email = $model->username.'@'.$_SERVER['SERVER_NAME'];
			}
			//$model->unit_level = $_POST['User']['unit_level'];
			//$profile->attributes=$_POST['Profile'];
			//$profile->user_id=0;
			if($model->validate()&&$profile->validate()) {
				$model->password=Yii::app()->controller->module->encrypting($model->password);
				if($model->save()) {
					$profile->user_id=$model->id;
					$profile->save();
				}
				//add user role
				if(isset($_POST['Authitem']) && isset($_POST['Authitem']['name'])){
					$role = $_POST['Authitem']['name'];
					$res = AuthItem::model()->find('name=:name',array(':name'=>$role));
					if(empty($res)) $role = 'master';
				}else{
					$role = 'admin';
				}
				Yii::import('application.modules.rights.controllers.AssignmentController');
		        $model = User::model()->findByPk($model->id);
		        $usermodule = Yii::app()->getModule('rights');
		        $authorizer = $usermodule->getAuthorizer();
		        $authorizer->attachUserBehavior($model);

		        $assignedItems = $authorizer->getAuthItems(null, $model->getId());
		        $assignments = array_keys($assignedItems);
		        $authorizer->authManager->assign($role, $model->getId());
				$item = $authorizer->authManager->getAuthItem($role);
				$item = $authorizer->attachAuthItemBehavior($item);
				
				$this->redirect(array('view','id'=>$model->id));
			} else $profile->validate();
		}
		
		$provinces = MtsysProvince::model()->findAll();
		$this->render('create',array(
			'model'=>$model,
			'profile'=>$profile,
			'provinces'=>$provinces,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();
		$profile=$model->profile;
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			//var_dump($_POST['User']);
			//exit;
		/*	switch($_POST['User']['unit_level']){
				case '1':
					$model->unit_id = $_POST['User']['PROVINCE_ID'];
					break;
				case '2':
					$model->unit_id = $_POST['User']['CITY_ID'];
					break;
				case '3':
					$model->unit_id = $_POST['User']['COUNTY_ID'];
					break;
				case '4':
					if(is_array($_POST['User']['BASE_ID'])){
						$model->unit_id = implode(',',$_POST['User']['BASE_ID']);	
					}else{
						$model->unit_id = $_POST['User']['BASE_ID'];
					}
					break;
			}*/
			if(empty($model->email)){
			$model->email = $model->username.'@'.$_SERVER['SERVER_NAME'];
			}
			//$profile->attributes=$_POST['Profile'];
			//$profile->user_id=0;
			if($model->validate()&&$profile->validate()) {
				$old_password = User::model()->notsafe()->findByPk($model->id);
				if ($old_password->password!=$model->password) {
					$model->password=Yii::app()->controller->module->encrypting($model->password);
					$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
				}
				if($model->save()) {
					$profile->user_id=$model->id;
					$profile->save();
				}
				//add user role
				if(isset($_POST['Authitem']) && isset($_POST['Authitem']['name'])){
					$role = $_POST['Authitem']['name'];
					$res = AuthItem::model()->find('name=:name',array(':name'=>$role));
					if(empty($res)) $role = 'master';
				}else{
					$role = 'admin';
				}
				
				Yii::import('application.modules.rights.controllers.AssignmentController');
				//delete all user relative role
				$sql = 'delete from authassignment where userid='.$model->id;
				$cmd = Yii::app()->db->createCommand($sql);
				$cmd->execute();
				//add role
				$model = User::model()->findByPk($model->id);
				$usermodule = Yii::app()->getModule('rights');
				$authorizer = $usermodule->getAuthorizer();
				$authorizer->attachUserBehavior($model);
			
				$assignedItems = $authorizer->getAuthItems(null, $model->getId());
				$assignments = array_keys($assignedItems);
				$authorizer->authManager->assign($role, $model->getId());
				$item = $authorizer->authManager->getAuthItem($role);
				$item = $authorizer->attachAuthItemBehavior($item);
			
				$this->redirect(array('view','id'=>$model->id));
			} else $profile->validate();
			//$profile->attributes=$_POST['Profile'];
					
/*			if($model->validate() && $profile->validate()) {
				$old_password = User::model()->notsafe()->findByPk($model->id);
				if ($old_password->password!=$model->password) {
					$model->password=Yii::app()->controller->module->encrypting($model->password);
					$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
				}
				$model->save();
				$profile->save();
				$this->redirect(array('view','id'=>$model->id));
			} else $profile->validate();*/
		}
		
		$this->render('update',array(
			'model'=>$model,
			'profile'=>$profile,
		));
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel();
			$profile = Profile::model()->findByPk($model->id);
			$profile->delete();
			$model->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax']))
				$this->redirect(array('/user/admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=User::model()->notsafe()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
}